package cn.bossfriday.fileserver;

import cn.bossfriday.common.plugin.PluginApplication;
import cn.bossfriday.common.plugin.PluginSpringContext;
import cn.bossfriday.fileserver.engine.StorageEngine;
import cn.bossfriday.fileserver.engine.StorageHandlerFactory;
import cn.bossfriday.fileserver.http.HttpFileServer;
import cn.bossfriday.im.common.PluginBootstrap;
import cn.bossfriday.im.common.conf.ConfigurationAllLoader;
import lombok.extern.slf4j.Slf4j;

import static cn.bossfriday.im.common.constant.ImConstant.BASE_PACKAGE_NAME;
import static cn.bossfriday.im.common.constant.ImConstant.SERVICE_NAME_FILE;

/**
 * FileServerBootstrap
 * <p>
 * 文件服务：负责文件上传和下载；
 *
 * @author chenx
 */
@Slf4j
@PluginApplication(name = SERVICE_NAME_FILE)
public class FileServerBootstrap extends PluginBootstrap {

    @Override
    protected void start() {
        try {
            StorageHandlerFactory.init();
            StorageEngine.getInstance().start();
            HttpFileServer.getInstance().start();
        } catch (InterruptedException e) {
            log.error("ServiceBootstrap.start() InterruptedException!", e);
            Thread.currentThread().interrupt();
        } catch (Exception ex) {
            log.error("ServiceBootstrap.start() error!", ex);
        }
    }

    @Override
    protected void stop() {
        try {
            StorageEngine.getInstance().stop();
            HttpFileServer.getInstance().stop();
        } catch (InterruptedException e) {
            log.error("ServiceBootstrap.stop() InterruptedException!", e);
            Thread.currentThread().interrupt();
        } catch (Exception ex) {
            log.error("ServiceBootstrap.stop() error!", ex);
        }
    }

    /**
     * 本地启动入口
     */
    public static void main(String[] args) {
        PluginSpringContext.initialize(BASE_PACKAGE_NAME);
        PluginBootstrap plugin = new FileServerBootstrap();
        plugin.startup(ConfigurationAllLoader.getInstance().getSystemConfig());
        Runtime.getRuntime().addShutdownHook(new Thread(plugin::shutdown));
    }
}
